<template>
    <el-config-provider>
        <el-container class="app_container">
            <el-header>
                <div class="d-flex justify-content-between">
                    <div class="hd fw-bold">
                        <div class="logo hstack">
                            <img src="@/assets/img/logo.png" alt="logo" />
                            <a>华中科技大学</a>
                        </div>
                    </div>
                    <!-- -->
                    <div class="menu-wrapper">
                        <!-- <el-icon @click="onToggleAside()">
              <Expand v-if="visibleState.aside" />
              <Fold v-else />
            </el-icon> -->
                        <!-- 一级目录 -->
                        <el-menu class="flex-grow-1" mode="horizontal" :default-active="activeMenuId"
                            @select="handleSelect">
                            <template v-for="(item, idx) of dataOfMenus">
                                <el-menu-item :index="item.id.toString()"
                                    :class="activeMenuId == item.id ? 'is-active' : ''">{{
                            item.title
                        }}</el-menu-item>
                            </template>
                        </el-menu>
                    </div>
                    <div class="d-flex align-items-center">
                        <!-- <img src="@/assets/img/home.svg" alt="logo" @click="onMenuCommand('home')" class="mr-sm-4" /> -->
                        <img src="@/assets/img/logout.svg" alt="logo" @click="onMenuCommand('logout')" />
                    </div>
                </div>
            </el-header>
            <el-container>
                <!-- {{dataOfSubMenus}} -->
                <!-- {{activeSubMenuId}} -->
                <el-aside :width="visibleState.aside ? '220px' : '0px'" class="d-flex flex-column"
                    v-show="visibleState.aside">
                    <el-menu :default-active="activeSubMenuId" class="flex-grow-1 aside-menu" @select="handleMenu">
                        <template v-for="(item, idx) of dataOfSubMenus">
                            <!-- 预留三级目录 -->
                            <template v-if="item.children && item.children.length">
                                <!-- 有子菜单 -->
                                <el-sub-menu :index="item.id.toString()">
                                    <template #title>
                                        <span>{{ item.title }}</span>
                                    </template>
                                    <el-menu-item :index="item2.id.toString()" v-for="(item2, idx2) of item.children"
                                        :key="idx2" @click="onClickMenuItem(item2)">
                                        {{ item2.title }}
                                    </el-menu-item>
                                </el-sub-menu>
                            </template>
                            <template v-else>
                                <!-- 二级目录 -->
                                <!-- 无子菜单 -->
                                <el-menu-item :index="item.id.toString()">
                                    <template #title>
                                        <span>{{ item.title }}</span>
                                    </template>
                                </el-menu-item>
                            </template>
                        </template>

                    </el-menu>
                </el-aside>
                <el-main>
                    <router-view></router-view>
                </el-main>
            </el-container>
        </el-container>

    </el-config-provider>
</template>

<script setup>
/**
 * 布局视图组件
 */
import { onMounted, ref, inject, provide, watch, onBeforeUnmount, nextTick } from 'vue';
import { useRouter, useRoute } from 'vue-router';
import { ElMessage, ElMessageBox } from 'element-plus';
import EsString from '@/utils/EsString';
import EsAjax from '@/utils/EsAjax';
import ApiUrls from '@/apis/index';
import MenuTabs from '@/components/menu-tabs/MenuTabs.vue';
import MenusJson from '@/mock/modules/Menus.json';
//config
import config from '@/config/index';
import pageEnum from '@/config/pageEnum';
//stores
import useAuthStore from '@/stores/useAuthStore';
import { useWebSocketStore } from '@/stores/useWebSocketStore';
// ======================================================
//                      变量声明
// ======================================================
const authStore = useAuthStore();
const socketStore = useWebSocketStore();
socketStore.connectWebSocket()
const subscribe = socketStore.$subscribe((mutation, state) => {
    // 我们就可以在此处监听store中值的变化，当变化为某个值的时候，去做一些业务操作之类的
    // console.error('mutation=======', mutation)
    // console.error('state=======', state)
    if (state.socketMessage) {
        try {

            // const socketMessage =`{
            //     "id": 0,
            //     "online": 0,
            //     "list": null,
            //     "event": "call",
            //     "data": {
            //         "remoteRoom": 102,
            //         "localUser": "lym"
            //     }
            // }`
            // const message = JSON.parse(socketMessage)
            const message = JSON.parse(state.socketMessage)
            // @Daily 现在有个功能需要优先开发一下。前端后后台建立ws连接后我会给你发类似下面的消息，如果你们收到消息有event且event为call，麻烦你们前端跳到roomid为remoteRoom的教室的详情页。可以实现吗？
            if (message.event == "call" && authStore.getLoginName() == message.data.localUser) {
                var query = {
                    id: message.data.remoteRoom
                }
                EsAjax.post(ApiUrls.roomData, query).then(res => {
                    if (res.data.code != 200) {
                        return;
                    }
                    // 点击跳转
                    localStorage.setItem("ROOM_DATA", JSON.stringify(res.data.data));
                    // console.log('router===', router)
                    router.push({
                        path: pageEnum.CLASSROOM_DETAIL,
                        query: { id: res.data.data.id }
                    })
                    onAsideFun(false)
                }).catch(err => {
                    // ElMessage.error(err.message);
                })

            } else {
                console.log("不一致，不用跳转");
            }



        } catch (error) {
            console.log(error)

        }
    }
}, { detached: false })  //第二个参数options对象，是各种配置参数
onBeforeUnmount(() => {
    // 关闭Socket
    socketStore.closeWebSocket()
    //停止订阅
    subscribe()
});

const router = useRouter();
const route = useRoute();
//一级目录
const dataOfMenus = ref([]);
//二级目录
const dataOfSubMenus = ref([]);
//以id问索引
const menuPathSave = ref({})
const menuIdSave = ref({})
//以当前url为索引记录信息
const menuCurPathSave = ref({})
//
const menuTabsRef = ref(null)
//横向一级目录
const activeMenuId = ref(null);
//左边二级目录
const activeSubMenuId = ref(null);
//是否显示左边aside
const visibleState = ref({
    aside: true
})
const defaultTabInfo = { id: 'startup', title: '仪表盘', path: '/index/index' };
let { home_url = "" } = route.query;
watch(() => route.path, (newPath, oldPath) => {

    nextTick(() => {
        if (newPath === '/bigscreen') {
            onAsideFun(false)
        }
        if (newPath === '/bigscreen') {
            onAsideFun(false)
        }
        if (newPath == pageEnum.CLASSROOM_DETAIL) {
            onAsideFun(false)
        }
        if (newPath && oldPath) {
            if (oldPath == pageEnum.CLASSROOM_DETAIL) {
                let _cur = menuCurPathSave.value[newPath]
                if (_cur) {
                    let { pid } = menuIdSave.value[_cur.id]
                    //二级目录
                    if (_cur.level == 2) {
                        let _menu = dataOfMenus.value.find((item) => item.id == pid)
                        if (_menu.children.length && _menu.children.length > 1) {
                            onAsideFun(true)
                        }
                    } else if (_cur.level == 3) {//三级目录
                        onAsideFun(true)
                    }
                }
            }


        }
    })
}, {
    immediate: true
});


// ======================================================
//                      点击操作
// ======================================================
// 点击一级目录
const handleSelect = (key) => {
    activeMenuId.value = key.toString();
    let nav = dataOfMenus.value.find((item) => item.id == key);
    loadChildMenu(nav)
};

// 点击二级目录
const handleMenu = (key) => {
    activeSubMenuId.value = key.toString();
    let nav = dataOfSubMenus.value.find((item) => item.id == key);
    if (nav) {
        onClickMenuItem(nav)
    }
};

// 点击菜单项目
const onClickMenuItem = (item) => {
    if (!item) {
        item = defaultTabInfo;
    }
    loadView(item);
}
// 为子组件提供创建标签页的方法
// 使用方法：
provide('addMenuIab', onClickMenuItem)

// 点击切换菜单命令
const onMenuCommand = (cmd) => {
    switch (cmd) {
        case 'logout':
            onLogout();
            break;
        case 'home':
            router.push('/home')
            break;
    }
}
// 点击退出登录按钮
const onLogout = () => {
    ElMessageBox.confirm('您确定要退出登录吗？', '操作确认', { confirmButtonText: '确定', cancelButtonText: '取消' }).then(res => {
        EsAjax.post(ApiUrls.logout)
        authStore.logout();
        router.push('/login');
    })
}
// 点击切换侧边栏按钮
const onToggleAside = () => {
    visibleState.value.aside = !visibleState.value.aside
}
// 点击切换侧边栏按钮
const onAsideFun = (flag = false) => {
    visibleState.value.aside = flag
}


// ======================================================
//                      处理事件
// ======================================================


// 加载指定的视图文件
const loadView = (item) => {
    // console.log('加载指定的视图文件 - 触发事件 item route.path', item, route.path)
    if (item.path && item.path != route.path) {
        // console.log('加载指定的视图文件 - 真正加载路由 item.path = ', item.path)
        router.push(item.path);
    }
    activeSubMenuId.value = item.id.toString();
}
//加载二级菜单
const loadChildMenu = (menu, index = 0) => {
    // console.log('加载二级菜单===', menu, index)
    onAsideFun(true)
    //默认二级级目录
    let child = menu.children || []
    dataOfSubMenus.value = child
    if (child && child.length) {
        if (child.length == 1 && typeof (child.children) == 'undefined') {
            onAsideFun(false)
        }
        let chi = child[index]
        // console.log('chi===', chi)

        if (chi.children && chi.children.length) {
            //三级目录
            // console.log('activeSubMenuId.value===', activeSubMenuId.value)
            let chi3 = child[index].children[0]
            activeSubMenuId.value = chi3.id.toString()
            loadView(chi3)
        } else {
            //二级目录
            activeSubMenuId.value = chi.id.toString()
            loadView(chi)
        }
    }
}

// 加载权限数据
const loadMenus = () => {
    return new Promise(resolve => {
        EsAjax.post(ApiUrls.resourceUsermenu).then(res => {
            // console.log('[INFO] BaseLayoutView 加载权限数据 res = ', res);
            if (res.data.code !== 200) {
                ElMessage.warning(res.data.msg);
                return;
            }
            // let { data } = MenusJson
            let { data } = res.data
            // console.log('data,datadatadata',data)
            let path = '', codes = [], menus = [], subMenus = [];
            data.forEach(item => {
                //一级
                menuPathSave.value[item.path] = { ...item, pid: 0 }
                menuIdSave.value[item.id] = { ...item, pid: 0 }
                subMenus = [];
                item.children.forEach((item2, idx) => {
                    //二级
                    menuIdSave.value[item2.id] = { ...item2, pid: item.id }
                    if (!item2.hidden) {
                        //三级目录
                        if (item2.component === "Layout") {
                            let _subMenus = { id: item2.id, title: item2?.meta?.title, children: [] }
                            item2.children.forEach(item3 => {
                                menuIdSave.value[item3.id] = { ...item3, pid: item2.id }
                                path = '/' + item3.path
                                let _thrMenus = { id: item3.id, title: item3?.meta?.title, path: path, level: 3 }
                                menuCurPathSave.value[path] = _thrMenus
                                _subMenus.children.push(_thrMenus);
                            })
                            subMenus.push(_subMenus);
                        } else {
                            // 二级目录
                            path = '/' + item2.path
                            let _subMenus = { id: item2.id, title: item2?.meta?.title, path: path, level: 2 }
                            menuCurPathSave.value[path] = _subMenus
                            subMenus.push(_subMenus);
                        }
                    }
                })

                menus.push({ id: item.id, title: item?.meta?.title, children: subMenus });
            })
            dataOfMenus.value = menus;
            console.log(dataOfMenus.value, '555');
            if (home_url) {
                setHomeUrl()
            } else {
                setPath()
            }
            resolve()
        }).catch(err => {
            ElMessage.error('网络错误：' + err.message);
        })
    })
}
const setHomeUrl = () => {
    if (menuPathSave.value[home_url]) {
        handleSelect(menuPathSave.value[home_url].id)
    }
}
// 刷新路由加载
const setPath = () => {
    if (route.path == '/') {
        //默认加载第一个路由
        let menu = dataOfMenus.value[0]
        //默认一级目录
        activeMenuId.value = menu.id.toString()
        //设置二级目录
        loadChildMenu(menu)
    } else {
        //有路由
        let _cur = menuCurPathSave.value[route.path]
        if (_cur) {
            let { pid } = menuIdSave.value[_cur.id]
            let _menuids = menuIdSave.value[pid]
            //二级目录
            if (_cur.level == 2) {
                let _menu = dataOfMenus.value.find((item) => item.id == pid)
                activeMenuId.value = pid.toString();
                var index = _menuids.children.findIndex((item) => item.id == _cur.id);
                loadChildMenu(_menu, index)
            } else if (_cur.level == 3) {//三级目录
                let _menu = dataOfMenus.value.find((item) => item.id == _menuids.pid)
                activeMenuId.value = _menuids.pid.toString();

                //设置二级目录
                onAsideFun(true)
                dataOfSubMenus.value = _menu.children || []
                //设置选中
                setTimeout(() => {
                    activeSubMenuId.value = _cur.id.toString();
                }, 100);
            }
        }
    }
}
// ======================================================
//                      生命周期
// ======================================================
// 保存权限代码数据
function getHomeUserInfo() {
    EsAjax.post(ApiUrls.homeUserinfo, {}).then(res => {
        if (res.data.code != 200) {
            ElMessage.warning(res.data.data + res.data.msg);
            return;
        }
        authStore.setLoginName(res.data.data?.KDXFLoginName)
    }).catch(err => {
    })
}


onMounted(() => {
    loadMenus()
    getHomeUserInfo()

    // loadMenus().then(() => {
    // menuTabsRef.value.init(defaultTabInfo);
    // });
})

</script>

<style lang="less" scoped>
:deep(.el-main) {
    padding: 0;
}

.el-aside {
    border: none !important;
}

.menu-wrapper {
    display: flex;
    flex-direction: row;
    list-style: none;
    -ml-flex-align: center;
    align-items: center;
    padding: 0;
    margin: 0 40px 0 40px;
    position: relative;
    min-width: 1300px;

    .menu-item {
        flex-shrink: 0;
    }

    >.menu-item+.menu-item {
        margin-left: 40px;
    }

    .menu-item-link {
        font-weight: 400;
        font-size: @text-df;
        line-height: 100px;
        cursor: pointer;
        position: relative;

        .el-icon {
            vertical-align: middle;
        }

        a {
            display: inline-block;
            color: @primary-text;
            transition: color 0.3s;

            :hover {
                color: app;
            }
        }

        .router-link-exact-active {
            font-weight: 600;

            span:after {
                content: "";
                display: block;
                height: 2px;
                position: absolute;
                width: 40px;
                left: calc(50% - 20px);
                bottom: 0px;
                background-color: @base-color;
            }
        }
    }
}

.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item,
.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-menu-item-group__title,
.aside-menu.el-menu--vertical:not(.el-menu--collapse):not(.el-menu--popup-container) .el-sub-menu__title {
    padding-left: 40px;
    font-size: 18px;
}

:deep(.el-sub-menu__title) {
    font-size: 20px;
}


:deep(.el-menu) {
    border: none;
    background-color: transparent !important;
}

:deep(.el-menu-item.is-active) {
    color: @base-color !important;
}

:deep(.el-menu-item) {
    background: transparent !important;
    color: #fff;
    font-size: 20px;
}

:deep(.el-sub-menu) {
    background: transparent !important;
}

:deep(.el-menu-item:active) {
    background: #fff;
}

:deep(.el-menu-item:hover) {
    background: #fff;
}

:deep(.el-menu-item) {
    background: #fff;
}

.el-menu--horizontal {
    border: none;
    justify-content: flex-start;
}

.el-menu--horizontal>.el-menu-item.is-active,
.el-menu--horizontal .el-menu-item:not(.is-disabled):focus,
.el-menu--horizontal .el-menu-item:not(.is-disabled):hover {
    background: url("../../assets/img/menuOn.svg") no-repeat center !important;
    background-size: 100% !important;
    border-bottom: none !important;
    color: #ffffff !important;
    width: 20%;
    // background-position: center;
}

.el-menu--horizontal>.el-menu-item {
    color: #9ba8b8;
    background: url("../../assets/img/menu.svg") no-repeat center !important;
    background-size: 100% !important;
    border-bottom: none !important;
    // background-position: center;
    padding: 0 40px;
    width: 20%;
}

// .el-menu--horizontal > .el-menu-item.is-active {
//   background: url("../../assets/img/menuOn.svg") no-repeat;
//   background-size: 100% !important;
//   background-position: center;
//   border-bottom: none !important;
//   color: #ffffff !important;
// }</style>
